package cc.rengu.igas.channel.wechat.core.service.trans;

import cc.rengu.igas.channel.wechat.common.constant.WechatConfigConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatParamConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTreeNodeConstant;
import cc.rengu.igas.channel.wechat.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.wechat.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.wechat.core.model.bean.IdcInfo;
import cc.rengu.igas.channel.wechat.core.service.base.AuthService;
import cc.rengu.igas.channel.wechat.facade.request.NuccIdcQueryRequest;
import cc.rengu.igas.channel.wechat.facade.response.NuccIdcQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.*;

/**
 * 网联idc查询
 */
public class NuccIdcQueryService extends AuthService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        NuccIdcQueryRequest idcQueryRequest = new NuccIdcQueryRequest();
        ConvertUtil.convertOutput(idcQueryRequest);
        return idcQueryRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;
        String secret = null;
        int timeQuery;
        NuccIdcQueryResponse idcQueryResponse = new NuccIdcQueryResponse();
        NuccIdcQueryRequest idcQueryRequest = (NuccIdcQueryRequest) request;
        String instId = idcQueryRequest.getHeader().getInstId();
        DstChannelInfo dstChannelInfo = (DstChannelInfo) xmlTreeUtil.getXmlTreeObjectValue(WechatTreeNodeConstant.DST_CHANNEL_INFO, DstChannelInfo.class);
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(WechatTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.WX_MCHNT_NO, dstChannelCfg.getProviderMchntNo());
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, idcQueryRequest.getHeader().getTxnNum());

        iReturnCode = schedule.callService(dstChannelInfo.getDstServiceName(), 0);
        if (0 != iReturnCode) {
            rglog.error("调用通道服务<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        /* 判断调用微信是否成功 */
        String errcode = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_CODE);
        String errmsg = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_MSG);
        if (null != errcode) {
            rglog.error("调用微信通道服务失败,errcode:<{}>,errmsg:<{}>", errcode, errmsg);
            throw new BizException(errcode, errmsg);
        }
        String idcInfos = xmlTreeUtil.getXmlTreeStringValue("idcInfos");
        rglog.debug("idcInfos=<{}>", idcInfos);
        List<IdcInfo> idcInfoList = JSON.parseArray(idcInfos, IdcInfo.class);
        StringBuilder stringBuilder = new StringBuilder();
        List<String> idcFlagList = new ArrayList<>();
        if (null != idcInfoList && idcInfoList.size() > 0) {
            Iterator<IdcInfo> itContact = idcInfoList.iterator();
            while (itContact.hasNext()) {
                IdcInfo idcInfo = itContact.next();
                rglog.error("idcFlag=[{}],status[{}]", idcInfo.getIdcFlag(), idcInfo.getStatus());
                if ("02".equals(idcInfo.getStatus())) {
                    continue;
                }
                idcFlagList.add(idcInfo.getIdcFlag());
            }
        }
        if (idcFlagList.size() != 0) {
            SysParamService sysParamService = new SysParamServiceImpl();
            SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                    WechatConfigConstant.NUCC_CONF_NODE, WechatConfigConstant.IDC_QUERY_TIME);
            if (sysParam == null) {
                rglog.error("为指定配置查询间隔，使用默认间隔时间");
                timeQuery = WechatParamConstant.ACCESS_TOKEN_EXPIRY_TIME;
            } else {
                timeQuery = Integer.parseInt(sysParam.getParamKey());
            }
            /*加载idc到redis缓存*/
            RedisUtil.onceSet(WechatParamConstant.NUCC_IDC_CAC, JSON.toJSONString(idcFlagList), timeQuery);
        }
        ConvertUtil.convertOutput(idcQueryResponse);
        idcQueryResponse.setIdcFlagList(idcFlagList);
        idcQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        idcQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(idcQueryResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        NuccIdcQueryResponse idcQueryResponse = (NuccIdcQueryResponse) response.getResult();
        ConvertUtil.convertInput(idcQueryResponse);
    }

}
